import Axios from "axios";
import moment from "moment";
import echarts from "echarts";
import * as serviceApi from "../common/service.config";
Axios.defaults.withcredentials = true;

const {
    BMap
} = window;
let map, globalMarker, horizontalPolyline, verticalPolyline, horizontalArrow, verticalArrow, referenceO, referenceA, referenceB, circles = [];
var myChart;

const addMarker = function (pointInfo, point, marker) {
    let label = new BMap.Label({
        id: pointInfo.id,
        type: pointInfo.moduleEnum
    }, {
        offset: new BMap.Size(20, 0)
    }); // 创建marker点的标记,这里注意下,因为百度地图可以对label样式做编辑,所以我这里吧重要的id放在了label(然后再隐藏)
    label.setStyle({
        display: "none"
    }); // 对label 样式隐藏, referenceA
    marker.setLabel(label); // 把label设置到maker上
    map.addOverlay(marker); // 把maker点添加到 地图上
    pointInfo["chargerMarker"] = marker; // 这里很重要,
    marker.addEventListener('click', function (e) {
        return;
        $("#info-panel").toggle(300); // div展开,关闭
        let tag = e.target.getLabel().content; // 点击maker点后
        // 获取label里面的内容
        let enumType = tag.type;
        let id = tag.id;
        loading(enumType, id);
    });
    let content = "";
    if (pointInfo.moduleEnum == "00") {
        content = `
        <h4 style='margin:0 0 5px 0;padding:0.2em 0;font-size:16px;font-weight:bold;text-align:center'>${pointInfo.sensorName}</h4>
        <p style='margin:0 0 15px 0;line-height:1.5;font-size:13px;text-indent:2em'>时间：${pointInfo.showDate}</p>
        <p style='margin:0 0 15px 0;line-height:1.5;font-size:13px;text-indent:2em'>x平移：${pointInfo.sensorNumber1}</p>
        <p style='margin:0 0 15px 0;line-height:1.5;font-size:13px;text-indent:2em'>y平移：${pointInfo.sensorNumber2}</p>
        <p style='margin:0 0 15px 0;line-height:1.5;font-size:13px;text-indent:2em'>H位移：${pointInfo.sensorNumber3}</p>
        <p style='margin:0 0 15px 0;line-height:1.5;font-size:13px;text-indent:2em'>平面位移：${pointInfo.sensorNumber4}</p>
        <p style='margin:0 0 15px 0;line-height:1.5;font-size:13px;text-indent:2em'>平行于目标累计偏移：${pointInfo.sensorNumber5}</p>
        <p style='margin:0 0 15px 0;line-height:1.5;font-size:13px;text-indent:2em'>垂直于目标累计偏移：${pointInfo.sensorNumber6}</p>
        <div style="position: absolute;left: 35%;top: 10%;">
            <div style="width: 400px;height: 300px;border: 2px dashed grey;margin: 0 0 10px 0" class="chartElement"></div>
            <button sensorNum="${pointInfo.sensorNumber}" sensorName="${pointInfo.sensorName}" class="btn2">位移过程</button>
            <button monitorId="${pointInfo.monitorId}" class="btn3">累计位移</button>
            <button sensorNum="${pointInfo.sensorNumber}" sensorName="${pointInfo.sensorName}" class="btn4">位移速率</button>
        </div>`
    } else {
        content = `
        <h4 style='margin:0 0 5px 0;padding:0.2em 0;font-size:16px;font-weight:bold;text-align:center'>${pointInfo.sensorName}</h4>
        <p style='margin:0 0 15px 0;line-height:1.5;font-size:13px;text-indent:2em'>经度：${point.lng.toFixed(8)}</p>
        <p style='margin:0 0 15px 0;line-height:1.5;font-size:13px;text-indent:2em'>纬度：${point.lat.toFixed(8)}</p>
        `
    }
    addPointLayer(marker, content);
};
const addPointLayer = function (marker, content) {
    let opts = {
        width: 650,
        height: 375,
        offset: new BMap.Size(0, -20)
    };
    addClickHandler(content, marker);

    function addClickHandler(content, marker) {
        marker.addEventListener("mouseover", function (e) {
            openInfo(content, e)
        });
        marker.addEventListener("mouseout", function (e) {
            // closeInfo(content, e);
        });
    }

    function openInfo(content, e) {
        let p = e.target;
        let point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
        let infoWindow = new BMap.InfoWindow(content, opts); // 创建信息窗口对象
        map.openInfoWindow(infoWindow, point); //开启信息窗口
        let ct = infoWindow.map.Bb.og;
        ct.style.position = "relative";
        const chartElement = ct.querySelector(".chartElement");
        myChart = echarts.init(chartElement);
        myChart.clear();
        let btn2 = ct.querySelector(".btn2");
        if (btn2)
            btn2.addEventListener("click", () => {
                myChart.showLoading();
                let sensorNum = btn2.getAttribute("sensorNum");
                let sensorName = btn2.getAttribute("sensorName");
                let singlePoint = (i) => {
                    let queryData = {
                        referenceName: "WGS84",
                        sensorNumber: sensorNum,
                        startTime: moment().subtract(i, "months").format("YYYY-MM-DD"),
                        endTime: moment().format("YYYY-MM-DD"),
                        timeType: "24"
                    }
                    Axios({
                        url: serviceApi.KB_API,
                        method: "post",
                        data: `appMsg={"parameter":"{\\"referenceName\\":\\"${queryData.referenceName}\\",\\"sensorNumber\\":\\"${queryData.sensorNumber}\\",\\"referenceType\\":\\"default\\",\\"startTime\\":\\"${queryData.startTime}\\",\\"endTime\\":\\"${queryData.endTime}\\",\\"timeType\\":\\"${queryData.timeType}\\"}","serviceCode":"planeAnalysis","timestamp":"","uuid":""}`
                    }).then(res => {
                        let list = res.data.parameter.list;
                        if (list.length == 0) {
                            singlePoint(i + 1)
                        } else {
                            myChart.hideLoading();
                            SinglePointAnalysis(
                                queryData,
                                list,
                                sensorName
                            );
                        }
                    })
                }
                singlePoint(1)
            })
        let btn3 = ct.querySelector(".btn3");
        if (btn3)
            btn3.addEventListener("click", () => {
                myChart.showLoading();
                let monitorId = btn3.getAttribute("monitorId");
                let queryData = {
                    startTime: moment().subtract(1, "months").format("YYYY-MM-DD"),
                    endTime: moment().format("YYYY-MM-DD"),
                    referenceName: "WGS84",
                    monitorId: monitorId,
                };
                Axios({
                    url: serviceApi.KB_API,
                    method: "post",
                    data: `appMsg={"parameter":"{\\"monitorId\\":\\"${queryData.monitorId}\\",\\"referenceName\\":\\"${queryData.referenceName}\\",\\"referenceType\\":\\"default\\",\\"startTime\\":\\"${queryData.startTime}\\",\\"endTime\\":\\"${queryData.endTime}\\"}","serviceCode":"queryTotalBD","timestamp":"","uuid":""}`,
                }).then((res) => {
                    let parameter = res.data.parameter;
                    myChart.hideLoading();
                    TotalAnalysis(queryData, parameter);
                });
            })
        let btn4 = ct.querySelector(".btn4");
        if (btn4)
            btn4.addEventListener("click", () => {
                myChart.showLoading();
                let sensorNum = btn2.getAttribute("sensorNum");
                let sensorName = btn2.getAttribute("sensorName");
                let speed = (i) => {
                    let queryData = {
                        startTime: moment().subtract(i, "months").format("YYYY-MM-DD"),
                        endTime: moment().format("YYYY-MM-DD"),
                        referenceName: "WGS84",
                        timeType: "24",
                        sensorNumber: sensorNum,
                    };
                    Axios({
                        url: serviceApi.KB_API,
                        method: "post",
                        data: `appMsg={"parameter":"{\\"referenceName\\":\\"${queryData.referenceName}\\",\\"referenceType\\":\\"default\\",\\"sensorNumber\\":\\"${queryData.sensorNumber}\\",\\"startTime\\":\\"${queryData.startTime}\\",\\"endTime\\":\\"${queryData.endTime}\\",\\"timeType\\":\\"${queryData.timeType}\\"}","serviceCode":"planeAnalysis","timestamp":"","uuid":""}`,
                    }).then((res) => {
                        let list = res.data.parameter.list;
                        if (list.length == 0) {
                            speed(i + 1)
                        } else {
                            myChart.hideLoading();
                            SpeedAnalysis(queryData, list, sensorName);
                        }
                    });
                }
                speed(1)
            })
        if (btn2) btn2.click();
    } //getPosition(),返回标注的地理坐标
    function closeInfo(content, e) {
        let p = e.target;
        let point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
        let infoWindow = new BMap.InfoWindow(content, opts); // 创建信息窗口对象
        map.closeInfoWindow(infoWindow, point); //开启信息窗口
    }
};

const SinglePointAnalysis = (queryData, list, sensorName) => {
    let xdata = [],
        ydata = [],
        hdata = [],
        pdata = [],
        theDate = [];
    for (let j = 0; j < list.length; j++) {
        xdata.push((list[j].xdata * 1000).toFixed(1));
        ydata.push((list[j].ydata * 1000).toFixed(1));
        hdata.push((list[j].hdata * 1000).toFixed(1));
        pdata.push((list[j].pdata * 1000).toFixed(1));
        theDate.push(moment(list[j].theDate / 1).format("YYYY-MM-DD HH:mm:ss"));
    }
    let chartOption = {
        title: {
            text: queryData.startTime +
                "至" +
                queryData.endTime +
                "内单点变形分析（" +
                queryData.referenceName +
                "）",
            textStyle: {
                fontSize: 14,
            },
            left: "center",
        },
        tooltip: {
            trigger: "axis",
        },
        legend: {
            top: 20,
            data: ["x平移", "y平移", "H位移", "平面位移"],
        },
        grid: {
            left: "10%",
            right: "10%",
            bottom: "3%",
            containLabel: true,
        },
        toolbox: {
            feature: {
                saveAsImage: {},
            },
            right: "5%",
            top: "5%",
        },
        xAxis: {
            name: "时间",
            type: "category",
            boundaryGap: false,
            data: theDate,
            axisLabel: {
                fontSize: 10
            }
        },
        yAxis: {
            name: "位移(mm)",
            type: "value",
            // axisLabel: {
            //     formatter: '{value} mm'
            // }
        },
        color: [
            "#027602",
            "#0101F6",
            "#840284",
            "#FF0000",
            "#27727B",
            "#FE8463",
            "#9BCA63",
            "#FAD860",
            "#F3A43B",
            "#60C0DD",
            "#D7504B",
            "#C6E579",
            "#F4E001",
            "#F0805A",
            "#26C0C0",
        ],
        series: [{
                name: "x平移",
                type: "line",
                smooth: true,
                lineStyle: {
                    normal: {
                        width: 3,
                    },
                },
                data: xdata,
            },
            {
                name: "y平移",
                type: "line",
                smooth: true,
                lineStyle: {
                    normal: {
                        width: 3,
                    },
                },
                data: ydata,
            },
            {
                name: "H位移",
                type: "line",
                smooth: true,
                lineStyle: {
                    normal: {
                        width: 3,
                    },
                },
                data: hdata,
            },
            {
                name: "平面位移",
                type: "line",
                smooth: true,
                lineStyle: {
                    normal: {
                        width: 3,
                    },
                },
                data: pdata,
            },
        ],
    };
    myChart.clear();
    myChart.setOption(chartOption);
    myChart.resize();
}

const TotalAnalysis = (queryData, parameter) => {
    let xdata = [],
        ydata = [],
        hdata = [],
        sensorName = [];
    for (let j = 0; j < parameter.length; j++) {
        xdata.push((parameter[j].gxData * 1000).toFixed(1));
        ydata.push((parameter[j].gyData * 1000).toFixed(1));
        hdata.push((parameter[j].hData * 1000).toFixed(1));
        let sensor = parameter[j].sensorName.trim("#", "left");
        sensorName.push(sensor);
    }
    let chartOption = {
        title: {
            text: "北斗站点累计变形分析（" + queryData.referenceName + "）",
            left: "center",
        },
        tooltip: {
            trigger: "axis",
            axisPointer: {
                type: "shadow",
            },
        },
        legend: {
            top: 30,
            data: ["x平移", "y平移", "H位移"],
        },
        grid: {
            left: "2%",
            right: "2%",
            bottom: "2%",
            containLabel: true,
        },
        toolbox: {
            feature: {
                saveAsImage: {},
            },
            right: "5%",
        },
        xAxis: {
            type: "category",
            boundaryGap: true,
            data: sensorName,
            textStyle: {
                fontSize: 10,
            },
            axisLabel: {
                //坐标轴刻度标签的相关设置。
                interval: 0,
                rotate: "-90",
            },
        },
        yAxis: {
            type: "value",
            name: "位移(mm)",
            nameLocation: "end",
            // axisLabel: {
            //     formatter: '{value} mm'
            // }
        },
        color: ["#018200", "#0200FE", "#81007F"],
        series: [{
                name: "x平移",
                type: "bar",
                width: "2",
                barGap: 0,
                data: xdata,
            },
            {
                name: "y平移",
                type: "bar",
                width: "2",
                data: ydata,
            },
            {
                name: "H位移",
                type: "bar",
                width: "2",
                data: hdata,
            },
        ],
    };
    myChart.clear();
    myChart.setOption(chartOption);
    myChart.resize();
}

const SpeedAnalysis = (queryData, list, sensorName) => {
    let xdata = [],
        ydata = [],
        hdata = [],
        theDate = [];
    for (let j = 0; j < list.length; j++) {
        xdata.push((list[j].xspeed * 1000).toFixed(1));
        ydata.push((list[j].yspeed * 1000).toFixed(1));
        hdata.push((list[j].hspeed * 1000).toFixed(1));
        theDate.push(moment(list[j].theDate / 1).format("YYYY-MM-DD HH:mm:ss"));
    }
    let chartOption = {
        title: {
            text: queryData.startTime +
                "至" +
                queryData.endTime +
                "内单点变形速率分析（" +
                queryData.referenceName +
                "）",
            textStyle: {
                fontSize: 14,
            },
            left: "center",
        },
        tooltip: {
            trigger: "axis",
        },
        legend: {
            top: 20,
            data: ["x平移速率", "y平移速率", "H位移速率"],
        },
        grid: {
            left: "10%",
            right: "10%",
            bottom: "3%",
            containLabel: true,
        },
        toolbox: {
            feature: {
                saveAsImage: {},
            },
            right: "5%",
            top: "5%",
        },
        xAxis: {
            name: "时间",
            type: "category",
            boundaryGap: false,
            data: theDate,
            axisLabel: {
                fontSize: 10,
            }
        },
        yAxis: {
            name: "位移（mm）",
            type: "value",
            // axisLabel: {
            //     formatter: '{value} mm'
            // }
        },
        color: [
            "#027602",
            "#0101F6",
            "#840284",
            "#FF0000",
            "#27727B",
            "#FE8463",
            "#9BCA63",
            "#FAD860",
            "#F3A43B",
            "#60C0DD",
            "#D7504B",
            "#C6E579",
            "#F4E001",
            "#F0805A",
            "#26C0C0",
        ],
        series: [{
                name: "x平移速率",
                type: "line",
                smooth: true,
                lineStyle: {
                    normal: {
                        width: 3,
                    },
                },
                data: xdata,
            },
            {
                name: "y平移速率",
                type: "line",
                smooth: true,
                lineStyle: {
                    normal: {
                        width: 3,
                    },
                },
                data: ydata,
            },
            {
                name: "H位移速率",
                type: "line",
                smooth: true,
                lineStyle: {
                    normal: {
                        width: 3,
                    },
                },
                data: hdata,
            },
        ],
    };
    myChart.clear();
    myChart.setOption(chartOption);
    myChart.resize();
}

const addReferenceLine = function (parameter) {
    map.removeOverlay(horizontalPolyline);
    map.removeOverlay(verticalPolyline);
    map.removeOverlay(horizontalArrow);
    map.removeOverlay(verticalArrow);
    map.removeOverlay(referenceA);
    map.removeOverlay(referenceB);
    map.removeOverlay(referenceO);
    if (typeof parameter.longitude1 == "undefined" || typeof parameter.longitude2 == "undefined" || typeof parameter.longitude3 == "undefined" ||
        typeof parameter.latitude1 == "undefined" || typeof parameter.latitude2 == "undefined" || typeof parameter.latitude3 == "undefined") {
        return false;
    }
    let points = [];
    let point1 = new BMap.Point(parameter.longitude1, parameter.latitude1);
    points.push(point1);
    let point2 = new BMap.Point(parameter.longitude2, parameter.latitude2);
    points.push(point2);
    let point3 = new BMap.Point(parameter.longitude3, parameter.latitude3);
    points.push(point3);
    kkCreateMap.translatePointList(points, function (data) {
        if (data.status === 0) {
            let pointO = new BMap.Point(data.points[0].lng, data.points[0].lat);
            let pointA = new BMap.Point(data.points[2].lng, data.points[2].lat);
            let pointB = new BMap.Point(data.points[1].lng, data.points[1].lat);
            // 创建polyline对象
            let horizontalPois = [
                pointO,
                pointB
            ];
            let verticalPois = [
                pointO,
                pointA
            ];
            horizontalPolyline = new BMap.Polyline(horizontalPois, {
                enableEditing: false, //是否启用线编辑，默认为false
                enableClicking: false, //是否响应点击事件，默认为true
                strokeWeight: '2', //折线的宽度，以像素为单位
                strokeOpacity: 0.8, //折线的透明度，取值范围0 - 1
                strokeColor: "#FF0000" //折线颜色
            });
            verticalPolyline = new BMap.Polyline(verticalPois, {
                enableEditing: false, //是否启用线编辑，默认为false
                enableClicking: false, //是否响应点击事件，默认为true
                strokeWeight: '2', //折线的宽度，以像素为单位
                strokeOpacity: 0.8, //折线的透明度，取值范围0 - 1
                strokeColor: "#FF0000" //折线颜色
            });
            map.addOverlay(horizontalPolyline);
            map.addOverlay(verticalPolyline);
            let horizontalPoints = getArrowPoints(horizontalPolyline);
            let verticalPoints = getArrowPoints(verticalPolyline);
            horizontalArrow = new BMap.Polyline(horizontalPoints, {
                enableEditing: false, //是否启用线编辑，默认为false
                enableClicking: false, //是否响应点击事件，默认为true
                strokeWeight: '2', //折线的宽度，以像素为单位
                strokeOpacity: 0.8, //折线的透明度，取值范围0 - 1
                strokeColor: "#FF0000" //折线颜色
            });
            verticalArrow = new BMap.Polyline(verticalPoints, {
                enableEditing: false, //是否启用线编辑，默认为false
                enableClicking: false, //是否响应点击事件，默认为true
                strokeWeight: '2', //折线的宽度，以像素为单位
                strokeOpacity: 0.8, //折线的透明度，取值范围0 - 1
                strokeColor: "#FF0000" //折线颜色
            });
            map.addOverlay(horizontalArrow);
            map.addOverlay(verticalArrow);
            referenceO = createReferenceLabel(pointO, "O", -20, -15); // 创建文本标注对象
            referenceA = createReferenceLabel(pointA, "A", -25, -15); // 创建文本标注对象
            referenceB = createReferenceLabel(pointB, "B", 5, -15); // 创建文本标注对象
            map.addOverlay(referenceO);
            map.addOverlay(referenceA);
            map.addOverlay(referenceB);
        }
    });
}

const getArrowPoints = function (polyline) {
    let linePoint = polyline.getPath();
    for (let i = 1; i < linePoint.length; i++) {
        let pixelStart = map.pointToPixel(linePoint[i - 1]);
        let pixelEnd = map.pointToPixel(linePoint[i]);
        //箭头长度
        let r = 10;
        //箭头和主线的夹角
        let angle = Math.PI / 7;
        //主线斜率，垂直时无斜率
        let delta = 0;
        //代码简洁考虑
        let param = 0;
        let pixelTemX, pixelTemY; //临时点坐标
        let pixelX, pixelY, pixelX1, pixelY1; //箭头两个点
        if (pixelEnd.x - pixelStart.x == 0) {
            //斜率不存在是时
            pixelTemX = pixelEnd.x;
            if (pixelEnd.y > pixelStart.y) {
                pixelTemY = pixelEnd.y - r;
            } else {
                pixelTemY = pixelEnd.y + r;
            }
            //已知直角三角形两个点坐标及其中一个角，求另外一个点坐标算法
            pixelX = pixelTemX - r * Math.tan(angle);
            pixelX1 = pixelTemX + r * Math.tan(angle);
            pixelY = pixelY1 = pixelTemY;
        } else {
            //斜率存在时
            delta = (pixelEnd.y - pixelStart.y) / (pixelEnd.x - pixelStart.x);
            param = Math.sqrt(delta * delta + 1);
            if ((pixelEnd.x - pixelStart.x) < 0) {
                //第二、三象限
                pixelTemX = pixelEnd.x + r / param;
                pixelTemY = pixelEnd.y + delta * r / param;
            } else {
                //第一、四象限
                pixelTemX = pixelEnd.x - r / param;
                pixelTemY = pixelEnd.y - delta * r / param;
            }
            pixelX = pixelTemX + Math.tan(angle) * r * delta / param;
            pixelY = pixelTemY - Math.tan(angle) * r / param;
            pixelX1 = pixelTemX - Math.tan(angle) * r * delta / param;
            pixelY1 = pixelTemY + Math.tan(angle) * r / param;
        }
        let pointArrow = map.pixelToPoint(new BMap.Pixel(pixelX, pixelY));
        let pointArrow1 = map.pixelToPoint(new BMap.Pixel(pixelX1, pixelY1));
        let arrowPoints = [];
        arrowPoints.push(pointArrow);
        arrowPoints.push(linePoint[i]);
        arrowPoints.push(pointArrow1);
        return arrowPoints;
    }
};
// 添加地图缩略图控件
const addControlFunc = function () {
    let overviewMapControl;
    let addControlFunc = function () {
        overviewMapControl = new BMap.OverviewMapControl({ // 添加地图类型控件，地图缩略图
            isOpen: true,
            anchor: BMAP_ANCHOR_BOTTOM_RIGHT,
        });
        // 添加地图类型控件,卫星控件
        let mapTypeControl = new BMap.MapTypeControl({
            anchor: BMAP_ANCHOR_TOP_RIGHT,
            offset: new BMap.Size(20, 10),
            mapTypes: [BMAP_SATELLITE_MAP, BMAP_NORMAL_MAP]
        });
        let cityListControl = new BMap.CityListControl({ // 添加地图类型控件，选择城市
            anchor: BMAP_ANCHOR_TOP_RIGHT,
            offset: new BMap.Size(20, 40)
        });
        map.addControl(overviewMapControl); // 添加地图类型控件，地图缩略图
        map.addControl(mapTypeControl); // 添加地图类型控件,卫星控件
        map.addControl(cityListControl); // 添加地图类型控件，选择城市
    };
    overviewMapControl = new BMap.OverviewMapControl({ // 添加地图类型控件，地图缩略图
        isOpen: true,
        anchor: BMAP_ANCHOR_BOTTOM_RIGHT,
    });
    // 添加地图类型控件,卫星控件
    let mapTypeControl = new BMap.MapTypeControl({
        anchor: BMAP_ANCHOR_TOP_RIGHT,
        offset: new BMap.Size(20, 10),
        mapTypes: [BMAP_SATELLITE_MAP, BMAP_NORMAL_MAP]
    });
    let cityListControl = new BMap.CityListControl({ // 添加地图类型控件，选择城市
        anchor: BMAP_ANCHOR_TOP_RIGHT,
        offset: new BMap.Size(20, 40)
    });
    map.addControl(overviewMapControl); // 添加地图类型控件，地图缩略图
    map.addControl(mapTypeControl); // 添加地图类型控件,卫星控件
    map.addControl(cityListControl); // 添加地图类型控件，选择城市
};


const createReferenceLabel = function (point, str, a, b) {
    let opts = {
        position: point, // 指定文本标注所在的地理位置
        offset: new BMap.Size(a, b) //设置文本偏移量
    }
    let label = new BMap.Label(str, opts); // 创建文本标注对象
    label.setStyle({
        color: "red",
        fontSize: "20px",
        fontFamily: "微软雅黑",
        backgroundColor: "",
    });
    return label;
}

const getCircleRadius = function (level) {
    switch (level) {
        case 1:
            return 1000000;
        case 2:
            return 500000;
        case 3:
            return 200000;
        case 4:
            return 100000;
        case 5:
            return 50000;
        case 6:
            return 20000;
        case 7:
            return 10000;
        case 8:
            return 5000;
        case 9:
            return 2500;
        case 10:
            return 2000;
        case 11:
            return 1000;
        default:
            return 500;
    }
}


export const kkCreateMap = {
    //初始化地图
    defaultInfo: {
        lng: null,
        lat: null,
        defaultMapLevel: null, //放大级别
        isShowVideo: null,
        videoUrl: null
    },
    init: function (dom) {
        const defaultMapType = sessionStorage.getItem("defaultMapType");
        if (defaultMapType != "undefined" && defaultMapType == 1) {
            map = new BMap.Map(dom, {
                mapType: BMAP_NORMAL_MAP
            });
        } else {
            map = new BMap.Map(dom, {
                mapType: BMAP_SATELLITE_MAP
            });
        }
        console.log(map);

        if (this.defaultInfo.lat === null) {
            this.defaultInfo.lat = 39.906995;
            this.defaultInfo.lng = 116.391555
        };
        map.clearOverlays();
        map.addEventListener("click", function (e) {
            console.log(e.point.lng + "," + e.point.lat);
        });
        let point = new BMap.Point(this.defaultInfo.lng, this.defaultInfo.lat);
        let that = this;
        this.translate(point, (data) => {
            if (data.status === 0) {
                point = new BMap.Point(data.points[0].lng, data.points[0].lat);
                map.centerAndZoom(point, that.defaultInfo.defaultMapLevel);
                map.enableScrollWheelZoom();
                map.setZoom(that.defaultInfo.defaultMapLevel + 1)
            }
            //去掉公路
            map.setMapStyle({
                styleJson: [{
                    "featureType": "highway",
                    "elementType": "all",
                    "stylers": {
                        "visibility": "off"
                    }
                }]
            });
        })
        // addControlFunc()
    },
    translate: function (pt, callBack) {
        let pts = [];
        pts.push(pt);
        const convertor = new BMap.Convertor();
        convertor.translate(pts, 1, 5, callBack)
    },
    translatePointList: function (points, translateCallback) {
        const convertor = new BMap.Convertor();
        convertor.translate(points, 1, 5, translateCallback);
    },
    setPointList: function (monitorList) {
        let that = this;
        //默认地图加载时定位点
        if (map.getZoom() > 14) {
            for (let i = 0; i < monitorList.length; i++) {
                // if (monitorList[i].monitorName == "江北新区猪头山滑坡点") {
                //     addNJOverlay();
                // }
                let pointList = monitorList[i].sensorList;
                for (let j = 0; j < pointList.length; j++) {
                    that.setPoint(pointList[j]);
                }
                // console.log(pointList);
            }
        }
        //添加缩放监听事件--缩放结束后触发
        map.addEventListener("zoomend", function () {
            map.clearOverlays(); //清除所有覆盖物
            let level = map.getZoom(); //获取缩放的大小值
            if (level <= 14) {
                for (let i = 0; i < monitorList.length; i++) {
                    that.setMonitor(monitorList[i], level);
                }
            } else {
                for (let i = 0; i < monitorList.length; i++) {
                    // if (monitorList[i].monitorName == "江北新区猪头山滑坡点") {
                    //     addNJOverlay();
                    // }
                    let pointList = monitorList[i].sensorList;
                    for (let j = 0; j < pointList.length; j++) {
                        that.setPoint(pointList[j]);
                    }
                }
            }
        });
    },
    setPoint: function (pointInfo) {
        let point = new BMap.Point(pointInfo.xoriginal, pointInfo.yoriginal);
        this.translate(point, function (data) {
            if (data.status === 0) {
                point = data.points[0];
                let bdIcon = new BMap.Icon(require("../assets/icon2/bd.png"), new BMap.Size(43, 66));
                let ytIcon = new BMap.Icon(require("../assets/icon2/yt.png"), new BMap.Size(43, 66));
                let qxIcon = new BMap.Icon(require("../assets/icon2/qx.png"), new BMap.Size(43, 66));
                let marker;
                if (pointInfo.moduleEnum == "00") {
                    marker = new BMap.Marker(point, {
                        icon: bdIcon,
                    });
                } else if (pointInfo.moduleEnum == "01") {
                    marker = new BMap.Marker(point, {
                        icon: ytIcon,
                    });
                } else if (pointInfo.moduleEnum == "02") {
                    marker = new BMap.Marker(point, {
                        icon: qxIcon,
                    });
                }
                addMarker(pointInfo, point, marker);
            }
        });
    },
    setMonitor: function (monitorInfo, level) {
        let point = new BMap.Point(monitorInfo.longitude, monitorInfo.latitude);
        this.translate(point, function (data) {
            if (data.status === 0) {
                point = data.points[0];
                let pointList = monitorInfo.sensorList;
                let beidouCount = 0;
                for (let j = 0; j < pointList.length; j++) {
                    if (pointList[j].moduleEnum == '00') {
                        beidouCount++;
                    }
                }
                let opts = {
                    position: point, // 指定文本标注所在的地理位置
                    offset: new BMap.Size(10, -50) //设置文本偏移量
                }
                let radius = getCircleRadius(level);
                let marker = new BMap.Marker(point);
                let circle = new BMap.Circle(point, radius);
                let label = new BMap.Label(monitorInfo.monitorName + "：共有" + beidouCount + "个北斗监测点", opts); // 创建文本标注对象
                label.setStyle({
                    background: "white",
                    color: "black",
                    fontSize: "18px",
                    lineHeight: "20px",
                    fontFamily: "微软雅黑",
                    padding: "5px",
                });
                map.addOverlay(circle);
                map.addOverlay(marker);
                map.addOverlay(label);
                circles.push({
                    circle: circle,
                    name: monitorInfo.monitorName
                });
                // console.log(circles)
                circle.addEventListener('click', function () {
                    console.log(this.point);
                    let p = new BMap.Point(this.point.lng, this.point.lat);
                    map.centerAndZoom(p, 20)
                })

            }
        });
    },
    setMapCenter: function (parameter) {
        if (typeof parameter.id == "undefined" || typeof parameter.moduleEnum == "undefined" || typeof parameter.longitude == "undefined" || typeof parameter.latitude == "undefined") {
            return false;
        }
        let point = new BMap.Point(parameter.longitude, parameter.latitude);
        this.translate(point, function (data) {
            if (data.status === 0) {
                map.removeOverlay(globalMarker);
                point = new BMap.Point(data.points[0].lng, data.points[0].lat);
                map.centerAndZoom(point, 19);
                map.enableScrollWheelZoom();
                addReferenceLine(parameter);
                let bdIcon = new BMap.Icon(require("../assets/icon2/bd2.png"), new BMap.Size(43, 68));
                let ytIcon = new BMap.Icon(require("../assets/icon2/yt2.png"), new BMap.Size(43, 68));
                let qxIcon = new BMap.Icon(require("../assets/icon2/qx2.png"), new BMap.Size(43, 68));
                let marker;
                if (parameter.moduleEnum == "00") {
                    marker = new BMap.Marker(point, {
                        icon: bdIcon,
                    });
                } else if (parameter.moduleEnum == "01") {
                    marker = new BMap.Marker(point, {
                        icon: ytIcon,
                    });
                } else if (parameter.moduleEnum == "02") {
                    marker = new BMap.Marker(point, {
                        icon: qxIcon,
                    });
                }
                globalMarker = marker;
                addMarker(parameter, point, marker); // 把maker点添加到 地图上
            }
        });
    }
};